package ngames.com.sushitv.action;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.internal.ImageRequest;
import com.facebook.login.widget.LoginButton;

import org.json.JSONObject;

import ngames.com.sushitv.R;
import ngames.com.sushitv.activity.LoginActivity;
import ngames.com.sushitv.activity.MainActivity;
import ngames.com.sushitv.activity.RegisterFBActivity;
import ngames.com.sushitv.base.BaseAction;
import ngames.com.sushitv.core.ModelCallback;
import ngames.com.sushitv.entity.UserInfo;
import ngames.com.sushitv.interfaces.DialogButtonListener;
import ngames.com.sushitv.tools.Constants;
import ngames.com.sushitv.tools.LogUtil;
import ngames.com.sushitv.view.DialogApp;

/**
 * Created by Administrator on 2016/3/29.
 */
public class FBLoginAction extends BaseAction {
    LoginFBUtilAction mLoginFBUtilAction;
    private ProgressDialog mProgressView;

    public FBLoginAction(Activity activity, View baseView) {
        super(activity, baseView);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mLoginFBUtilAction != null) {
            mLoginFBUtilAction.onActivityResult(requestCode, resultCode, data);
        }
    }

    public void loginFB() {
        if (mLoginFBUtilAction == null) {
            LoginButton fbLoginButton = (LoginButton) findViewById(R.id.btn_fb);
            mLoginFBUtilAction = new LoginFBUtilAction(mActivity, null);
            mLoginFBUtilAction.onCreate();
            mLoginFBUtilAction.setFBLoginButton(fbLoginButton);
            mLoginFBUtilAction.setLoginFBCallBack(new LoginFBUtilAction.LoginFBCallBack() {
                @Override
                public void onLoginFB(int result, AccessToken accessToken) {
                    if (accessToken == null && result == 1) {
                        Toast.makeText(getAppApplication(), "Failed", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    requestFaceBookInfo(accessToken);
                }
            });
        }
        mLoginFBUtilAction.loginFB();
    }

    /**
     * FB个人信息获取网络请求
     */
    private void requestFaceBookInfo(final AccessToken accessToken) {
        if (accessToken == null) {
            return;
        }
        if (mProgressView == null) {
            mProgressView = new ProgressDialog(mActivity);
            mProgressView.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressView.setMessage("Login Facebook...");
        }
        mProgressView.show();
        // make request to the /me API
        GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject user, GraphResponse response) {
                // TODO Auto-generated method stub
                String name = null;
                String email = null;
                if (user != null) {
                    LogUtil.d("FBLoginAction", "user = " + user.toString());
                    String id = user.optString("id");//
                    name = user.optString("name");
                    email = user.optString("email");
                } else {
                    LogUtil.d("FBLoginAction", "user null");
                }

                UserInfo userInfo = new UserInfo();
                userInfo.setUid(accessToken.getUserId());
                Uri uri = ImageRequest.getProfilePictureUri(accessToken.getUserId(), 300, 300);
                userInfo.setAvatar(uri.toString());
                userInfo.setEmail(email);
                loginByFB(userInfo);
            }
        });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id, name, email, gender, birthday");
        request.setParameters(parameters);
        request.executeAsync();
    }

    private void loginByFB(final UserInfo userInfo) {
        if (mProgressView != null) {
            mProgressView.cancel();
        }
        getAppModel().getUserService().loginFB(userInfo, new ModelCallback<UserInfo>() {
            @Override
            public void onBeforeRequest(String urlTag) {

            }

            @Override
            public void onSuccess(UserInfo data) {
                mProgressView.cancel();
                mActivity.startActivity(new Intent(mActivity, MainActivity.class));
//                RegisterFBActivity.goRegisterFBActivity(mActivity, Constants.ACCOUNT_TYPE_FB, userInfo);
            }

            @Override
            public void onFailure(String errorEvent, String message) {
                mProgressView.cancel();
                if ("3321".equals(errorEvent)) {
                    RegisterFBActivity.goRegisterFBActivity(mActivity, Constants.ACCOUNT_TYPE_FB, userInfo);
                } else if ("3313".equals(errorEvent)) {
                    final DialogApp activationDialog = new DialogApp(mActivity);
                    activationDialog.setMessage("登录注册邮箱激活账号！");
                    activationDialog.setRightBtn("OK", new DialogButtonListener() {
                        @Override
                        public void onClick() {
                            activationDialog.dismiss();
                            mActivity.startActivity(new Intent(mActivity, LoginActivity.class));
                        }
                    });
                    activationDialog.show();
                } else {
                    Toast.makeText(getAppApplication(), "login error", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
